<template>
  <view>
    <view class="loading-box">
      <u-loading-page
        :loading="load"
        loading-text="蓝牙连接中..."
        loading-mode="spinner"
        color="#ffffff"
        bg-color="rgba(0, 0, 0, 0.5)"
        loading-color="#ffffff"
        :z-index="20000"
      >
      </u-loading-page>
    </view>

    <view class="icu-content">
      <u-overlay :show="showSend" :opacity="0.8">
        <view class="warp">
          <span>正在写入中请稍等...</span>
        </view>
      </u-overlay>
      <view class="icu-btn-box">
        <view class="btn">
          <u-button
            type="primary"
            icon="setting"
            size="large"
            :text="linkStatus ? '蓝牙已连接' : '连接蓝牙'"
            @click="openShow"
          >
          </u-button>
        </view>

        <view class="btn">
          <u-button
            type="success"
            icon="file-text"
            size="large"
            text="读取参数"
            @click="readParameters"
          >
          </u-button>
        </view>
        <view class="btn">
          <u-button
            type="warning"
            icon="edit-pen"
            size="large"
            text="写入参数"
            @click="okPreserveData"
            color="linear-gradient(to right, rgb(217, 217, 0),rgb(217, 217, 0))"
          ></u-button>
        </view>
        <view class="btn">
          <u-button
            type="warning"
            icon="reload"
            size="large"
            text="更新WEB"
            @click="undateWeb"
            color="linear-gradient(to right, rgb(111, 217, 191),rgb(111, 217, 191))"
          ></u-button>
        </view>
        <view class="btn">
          <u-button
            type="error"
            icon="more-circle"
            size="large"
            text="重启设备"
            @click="rebootDevice"
          ></u-button>
        </view>
        <view class="btn">
          <u-button
            type="warning"
            icon="edit-pen-fill"
            size="large"
            :text="ipSelectTit"
            @click="openShowConfigure"
          >
          </u-button>
        </view>
        <view class="btn">
          <u-button
            type="error"
            icon="close-circle"
            size="large"
            text="关闭蓝牙"
            @click="closeLy"
            color="linear-gradient(to right, rgb(170, 169, 187),rgb(170, 169, 187))"
          ></u-button>
        </view>
      </view>
      <view class="icu-inp-box">
        <u-form labelPosition="left" :model="form" :rules="rules" ref="uForm">
          <u-form-item labelWidth="100" label="设备版本:" borderBottom>
            <u-input
              disabled="true"
              placeholder="app:1.1|boot:1"
              v-model="form.version"
              border="none"
            >
            </u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="设备名称:"
            borderBottom
            prop="equipmentName"
          >
            <u-input
              placeholder="可输入字母、数字和符号，不允许空格"
              v-model="form.equipmentName"
              border="none"
            ></u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="IP地址:"
            borderBottom
            prop="ipAdderss"
          >
            <u-input
              type="digit"
              placeholder="192.168.8.10"
              v-model="form.ipAdderss"
              border="none"
            >
            </u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="子网掩码:"
            borderBottom
            prop="mask"
          >
            <u-input
              type="digit"
              placeholder="255.255.255.0"
              v-model="form.mask"
              border="none"
            ></u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="默认网关:"
            borderBottom
            prop="gateway"
          >
            <u-input
              type="digit"
              placeholder="192.168.8.1"
              v-model="form.gateway"
              border="none"
            ></u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="IPV4_DNS:"
            borderBottom
            prop="ipv4"
          >
            <u-input
              type="digit"
              placeholder="192.168.8.1"
              v-model="form.ipv4"
              border="none"
            ></u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="MQTT服务IP:"
            borderBottom
            prop="mqttIp"
          >
            <u-input
              type="digit"
              placeholder="222.128.47.96"
              v-model="form.mqttIp"
              border="none"
            >
            </u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="MQTT端口:"
            borderBottom
            prop="mqttPort"
          >
            <u-input
              type="digit"
              placeholder="1883"
              v-model="form.mqttPort"
              border="none"
            >
            </u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="配置服务IP:"
            borderBottom
            prop="serviceIp"
          >
            <u-input
              type="digit"
              placeholder="192.168.10.25"
              v-model="form.serviceIp"
              border="none"
            >
            </u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="配置端口:"
            borderBottom
            prop="servicePort"
          >
            <u-input
              type="digit"
              placeholder="8888"
              v-model="form.servicePort"
              border="none"
            >
            </u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="MQTT用户名:"
            borderBottom
            prop="mqttuser"
          >
            <u-input
              placeholder="仅限制英文字符与数字"
              v-model="form.mqttuser"
              border="none"
            >
            </u-input>
          </u-form-item>
          <u-form-item
            labelWidth="100"
            label="MQTT密码:"
            borderBottom
            prop="mqttpassword"
          >
            <u-input
              placeholder="可输入字母、数字和符号"
              v-model="form.mqttpassword"
              border="none"
            >
            </u-input>
          </u-form-item>
        </u-form>
        <u-action-sheet
          :show="showSex"
          :actions="actions"
          title="请选择性别"
          description="如果选择保密会报错"
          @close="showSex = false"
          @select="sexSelect"
        >
        </u-action-sheet>
      </view>
    </view>

    <u-modal
      :negativeTop="150"
      :show="show"
      title="选择要连接的蓝牙设备"
      @cancel="closeShow"
      :showCancelButton="true"
      :showConfirmButton="false"
    >
      <view class="bluetooth-device-list">
        <view v-if="connectDeviceList.length === 0" class="no-device">
          <text>正在搜索蓝牙设备...</text>
          <u-loading-icon mode="flower"></u-loading-icon>
        </view>
        <view
          v-for="device in connectDeviceList"
          :key="device.deviceId"
          class="device-item"
          @click="createBlue(device)"
        >
          <view class="device-info">
            <text class="device-name">{{
              device.localName || device.name || "未知设备"
            }}</text>
            <text class="device-id">{{ device.deviceId }}</text>
          </view>
          <view class="device-signal">
            <text class="signal-strength">信号: {{ device.RSSI }}m</text>
          </view>
        </view>
        <view class="refresh-btn" @click="refreshDeviceList">
          <u-button type="primary" size="small" text="刷新设备列表"></u-button>
        </view>
      </view>
    </u-modal>

    <u-picker
      :show="showConfigure"
      :columns="columns"
      keyName="label"
      @close="closeShowConfigure"
      @cancel="closeShowConfigure"
      @confirm="confirm"
    >
    </u-picker>
  </view>
</template>
  
  <script>
export default {
  data() {
    return {
      rules: {
        equipmentName: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern: /^[0-9a-zA-Z!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]+$/g,
            // 正则检验前先将值转为字符串
            transform(value) {
              return String(value);
            },
            message: "可包含字母、数字和符号，不允许空格",
          },
        ],
        ipAdderss: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern:
              /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
            // 正则检验前先将值转为字符串
            message: "请输入正确的IP地址",
          },
        ],
        mask: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern:
              /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
            // 正则检验前先将值转为字符串
            message: "请输入正确的子网掩码",
          },
        ],
        gateway: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern:
              /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
            // 正则检验前先将值转为字符串
            message: "请输入正确的默认网关",
          },
        ],
        ipv4: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern:
              /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
            // 正则检验前先将值转为字符串
            message: "请输入正确的IPV4",
          },
        ],
        mqttIp: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern:
              /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
            // 正则检验前先将值转为字符串
            message: "请输入正确的MQTT IP",
          },
        ],
        mqttPort: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern: /^\d+$/,
            // 正则检验前先将值转为字符串
            message: "请输入正确的端口号",
          },
        ],
        serviceIp: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern:
              /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
            // 正则检验前先将值转为字符串
            message: "请输入正确的服务IP",
          },
        ],
        servicePort: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern: /^\d+$/,
            // 正则检验前先将值转为字符串
            message: "请输入正确的端口号",
          },
        ],
        mqttuser: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern: /^[0-9a-zA-Z]*$/g,
            // 正则检验前先将值转为字符串
            transform(value) {
              return String(value);
            },
            message: "只能包含字母或数字",
          },
        ],
        mqttpassword: [
          {
            required: true,
            message: "此为必填字段",
            trigger: ["change", "blur"],
          },
          {
            pattern: /^[0-9a-zA-Z!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/g,
            // 正则检验前先将值转为字符串
            transform(value) {
              return String(value);
            },
            message: "可包含字母、数字和常用符号",
          },
        ],
      },
      showSend: false,

      connectDeviceList: [], //连接蓝牙设备列表
      ipSelectTit: "配置IP选择",
      showConfigure: false,
      columns: [
        [
          {
            label: "连接指定IP",
            value: "0",
          },
          {
            label: "等待广播IP",
            value: "1",
          },
          {
            label: "广播互切",
            value: "2",
          },
          {
            label: "关闭连接",
            value: "3",
          },
        ],
      ],
      show: false,

      linkStatus: false,

      load: false,
      form: {
        version: "",
        equipmentName: "",
        ipAdderss: "",
        mask: "255.255.254.0", // 掩码
        gateway: "50.50.21.254", // 网关
        ipv4: "50.50.21.254",
        mqttIp: "50.50.21.1",
        mqttPort: "1883", // mqtt端口
        serviceIp: "50.50.21.1",
        servicePort: "8888",
        configureIp: "", // 配置IP
        mqttuser: "admin", // mqtt用户名
        mqttpassword: "admin", // mqtt密码
      },
      servicesUuid: [], // 蓝牙服务的UUID
      deviceId: "", // 蓝牙的ID
      // 接收的ID
      notifyserviceId: "",
      notifycharacteristicId: "",
      // 发送的ID
      sendserviceId: "",
      sendcharacteristicId: "",
      // 目标服务缓存
      targetWriteService: null, // FFE5写入服务
      targetNotifyService: null, // FFE0通知服务
    };
  },
  mounted() {
    this.$refs.uForm.setRules(this.rules);
    // 监听蓝牙连接状态变化
    this.initBluetoothStateListener();
  },
  onReady() {},
  onLoad() {
    //this.closeLy()
  },
  methods: {
    // 初始化蓝牙状态监听
    initBluetoothStateListener() {
      let that = this;

      // 监听蓝牙连接状态变化
      uni.onBLEConnectionStateChange((res) => {
        console.log("蓝牙连接状态变化:", res);
        if (res.deviceId === that.deviceId) {
          if (!res.connected) {
            // 连接断开
            that.linkStatus = false;
            that.deviceId = "";
            that.sendserviceId = "";
            that.sendcharacteristicId = "";
            that.notifyserviceId = "";
            that.notifycharacteristicId = "";

            uni.showToast({
              title: "蓝牙连接已断开",
              icon: "none",
              duration: 2000,
            });

            console.log("蓝牙连接断开，已重置相关状态");
          }
        }
      });

      // 监听蓝牙适配器状态变化
      uni.onBluetoothAdapterStateChange((res) => {
        console.log("蓝牙适配器状态变化:", res);
        if (!res.available) {
          that.linkStatus = false;
          that.deviceId = "";
          uni.showToast({
            title: "蓝牙适配器不可用",
            icon: "none",
          });
        }
      });
    },

    // 更新web
    undateWeb() {
      if (this.linkStatus) {
        this.sendMy(`100401ffffff`);
      } else {
        uni.$u.toast("请先连接蓝牙！");
      }
    },
    confirm(e) {
      this.showConfigure = false;
      this.form.configureIp = e.value[0].label;
      this.ipSelectTit = e.value[0].label;

      let out = e.value[0].value.toString(16);
      if (this.linkStatus) {
        this.sendMy(`10230${out}00ffffff`);
      } else {
        uni.$u.toast("请先连接蓝牙！");
      }
    },
    closeShowConfigure() {
      this.showConfigure = false;
    },
    openShowConfigure() {
      this.showConfigure = true;
    },
    // 关闭蓝牙
    closeLy() {
      let that = this;
      uni.closeBluetoothAdapter({
        success(res) {
          that.linkStatus = false;
          uni.$u.toast("蓝牙已关闭！");
        },
      });
    },

    // 初始化蓝牙适配器用于连接
    initAdapterForConnect() {
      let that = this;
      uni.openBluetoothAdapter({
        success: function (res) {
          console.log(res, "蓝牙初始化成功");
          that.startTargetDeviceSearch();
        },
        fail: function (msg) {
          console.error("蓝牙初始化失败:", msg);
          if (msg.errMsg && msg.errMsg.includes("already opened")) {
            // 如果是已经打开的错误，直接开始搜索
            console.log("蓝牙适配器已经打开，直接开始搜索目标设备");
            that.startTargetDeviceSearch();
          } else {
            uni.$u.toast("蓝牙初始化失败，请检查蓝牙权限和蓝牙是否开启");
            that.load = false;
          }
        },
      });
    },

    // 关闭蓝牙附近搜索
    stopBlueSurch() {
      uni.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log("停止搜索---", res);
        },
      });
    },
    // 连接蓝牙设备
    createBlue(data) {
      let that = this;
      this.load = true;
      console.log("进入到了连接蓝牙里面");
      uni.createBLEConnection({
        deviceId: data.deviceId,
        success(res) {
          that.linkStatus = true;
          that.load = false;
          that.show = false;
          uni.$u.toast("连接成功！");
          // 连接成功后关闭蓝牙搜索
          that.deviceId = data.deviceId;
          that.lyName = `蓝牙已连接`;
          // 关闭蓝牙搜索
          that.stopBlueSurch();
          // 去获取服务的UUID
          that.getServiceId();
        },
        fail(err) {
          that.linkStatus = false;
          that.load = false;
          uni.$u.toast("连接失败！");
          // 关闭
          that.stopBlueSurch();
          console.error(err);
        },
      });
    },
    // 获取蓝牙所有服务的UUID
    getServiceId() {
      var that = this;
      console.log(that.deviceId, "deviceId");
      uni.getBLEDeviceServices({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: that.deviceId,
        success: function (res) {
          console.log("获取蓝牙的所有服务UUID:", res);

          // 筛选目标服务：FFE5(写入) 和 FFE0(通知)
          let writeService = null;
          let notifyService = null;

          res.services.forEach((service) => {
            const serviceUuid = service.uuid;
            console.log(serviceUuid);

            if (serviceUuid.includes("FFE5")) {
              // 写入
              console.log("FFE5:", serviceUuid);
              writeService = service;
            } else if (serviceUuid.includes("FFE0")) {
              // 通知
              console.log("FFE0:", serviceUuid);
              notifyService = service;
            }
          });

          // 保存服务信息供后续使用
          that.targetWriteService = writeService;
          that.targetNotifyService = notifyService;

          that.getCharacteId();
        },
        fail: function (err) {
          console.error("获取蓝牙服务失败:", err);
          uni.$u.toast("获取蓝牙服务失败");
        },
      });
    },
    // 判断uuid的读写功能
    getCharacteId() {
      var that = this;
      uni.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: that.deviceId,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
        serviceId: that.targetWriteService.uuid,
        success: function (res) {
          for (var j = 0; j < res.characteristics.length; j++) {
            var model = res.characteristics[j];
            const uuid = model.uuid.toUpperCase();

            if (uuid.includes("FFE9") && model.properties.write) {
              console.log("✅ 找到FFE9写入特征值:", uuid);
              that.sendserviceId = that.targetWriteService.uuid;
              that.sendcharacteristicId = model.uuid;
              break;
            }
          }
        },
      });

      uni.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: that.deviceId,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
        serviceId: that.targetNotifyService.uuid,
        success: function (res) {
          for (var j = 0; j < res.characteristics.length; j++) {
            var model = res.characteristics[j];
            const uuid = model.uuid.toUpperCase();
            if (
              uuid.includes("FFE4") &&
              (model.properties.notify || model.properties.indicate)
            ) {
              that.notifyserviceId = that.targetNotifyService.uuid;
              that.notifycharacteristicId = model.uuid;
              that.notifyUuid = model.uuid;
              that.startNotice();
            }
          }
        },
      });
    },
    // 发送指令
    sendMy(val, cb) {
      if (!this.linkStatus) {
        return uni.$u.toast("请先连接蓝牙！");
      }

      var that = this;

      // 检查必要的参数是否存在
      if (!that.deviceId || !that.sendserviceId || !that.sendcharacteristicId) {
        console.log("蓝牙参数不完整:", {
          deviceId: that.deviceId,
          sendserviceId: that.sendserviceId,
          sendcharacteristicId: that.sendcharacteristicId,
        });
        uni.$u.toast("蓝牙连接异常，请重新连接");
        return;
      }

      // 写入前先验证蓝牙连接状态
      uni.getBluetoothAdapterState({
        success(adapterRes) {
          if (!adapterRes.available) {
            that.linkStatus = false;
            uni.$u.toast("蓝牙适配器不可用，请重新连接");
            return;
          }

          //this.string2buffer-->字符串转换成ArrayBufer（设备接收数据的格式ArrayBufer）
          var buff = that.string2buffer(val);

          uni.writeBLECharacteristicValue({
            deviceId: that.deviceId,
            serviceId: that.sendserviceId,
            characteristicId: that.sendcharacteristicId,
            value: buff,
            success: function (res) {
              console.log("指令发送成功:", val, res);
              uni.$u.toast("指令发送成功！");
            },
            fail: function (err) {
              console.log("当前写入参数:", {
                deviceId: that.deviceId,
                serviceId: that.sendserviceId,
                characteristicId: that.sendcharacteristicId,
                data: val,
              });

              // 根据错误码处理
              if (err.errCode === 10006) {
                // 写入失败，可能连接断开
                that.linkStatus = false;
                uni.showModal({
                  title: "蓝牙写入失败",
                  content: "设备连接已断开或不支持写入操作，请重新连接设备",
                  showCancel: false,
                });
              } else if (err.errCode === 10004) {
                // 服务不可用，可能需要重新获取特征值
                uni.showModal({
                  title: "服务不可用",
                  content: "蓝牙服务异常，请重新连接设备",
                  showCancel: false,
                });
              } else {
                uni.$u.toast("指令发送失败，请检查蓝牙连接");
              }
            },
            complete: function () {
              console.log("complete");
              if (cb) {
                setTimeout(() => {
                  cb();
                }, 1000);
              }
            },
          });
        },
        fail() {
          that.linkStatus = false;
          uni.$u.toast("蓝牙适配器异常，请重新连接");
        },
      });
    },
    // 接收设备返回的数据
    startNotice() {
      var that = this;
      uni.notifyBLECharacteristicValueChange({
        state: true, // 启用 notify 功能
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: that.deviceId,
        // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
        serviceId: that.notifyserviceId,
        // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
        characteristicId: that.notifycharacteristicId, //第一步 开启监听 notityid  第二步发送指令 write
        success(res) {
          //接收蓝牙返回消息
          uni.onBLECharacteristicValueChange((sjRes) => {
            // 此时可以拿到蓝牙设备返回来的数据是一个ArrayBuffer类型数据，
            // 所以需要通过一个方法转换成字符串
            var nonceId = that.ab2hex(sjRes.value); //10.0
            console.log(nonceId, "returnvalue");
            that.hexToString(nonceId);
          });
        },
        fail(err) {
          console.log(err);
        },
      });
    },
    // 将ArrayBuffer转换成字符串
    ab2hex(buffer) {
      const hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ("00" + bit.toString(16)).slice(-2);
        }
      );
      return hexArr.join("");
    },
    // 将字符串转换成ArrayBufer
    string2buffer(str) {
      if (!str) return null;

      // 确保字符串长度是偶数
      if (str.length % 2 !== 0) {
        console.error("十六进制字符串长度必须是偶数:", str);
        return null;
      }

      // 创建字节数组
      let bytes = [];
      for (let i = 0; i < str.length; i += 2) {
        let hexByte = str.substr(i, 2);
        let byte = parseInt(hexByte, 16);

        // 检查转换是否成功
        if (isNaN(byte)) {
          console.error("无效的十六进制字符:", hexByte);
          return null;
        }

        bytes.push(byte);
      }

      console.log("转换前字符串:", str);
      console.log("转换后字节数组:", bytes);

      // 创建ArrayBuffer
      return new Uint8Array(bytes).buffer;
    },
    // 重启设备
    rebootDevice() {
      let that = this;
      that.sendMy("100301ffffff");
    },
    // 读取参数
    readParameters() {
      let that = this;
      that.sendMy("100101ffffff");
      setTimeout(() => {
        that.startNotice();
      }, 1000);
    },
    // 写入参数
    writeInData() {
      let that = this;
      that.sendMy("100201ffffff");
    },
    // 将16进制转为 字符串
    hexToString(hex) {
      let str = "";
      for (let i = 0; i < hex.length; i += 2) {
        str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
      }
      let data = this.utf8to16(str);
      console.log(data, "utf-8to16");
      this.echoData(data);
    },

    // 处理中文乱码问题
    utf8to16(str) {
      var out, i, len, c;
      var char2, char3;
      out = "";
      len = str.length;
      i = 0;
      while (i < len) {
        c = str.charCodeAt(i++);
        switch (c >> 4) {
          case 0:
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
            out += str.charAt(i - 1);
            break;
          case 12:
          case 13:
            char2 = str.charCodeAt(i++);
            out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));
            break;
          case 14:
            char2 = str.charCodeAt(i++);
            char3 = str.charCodeAt(i++);
            out += String.fromCharCode(
              ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0)
            );
            break;
        }
      }
      return out;
    },
    // 将收到的数据进行分割回显
    echoData(item) {
      console.log("返回来的数据", item);
      let that = this;
      let arr = item.split("=");
      switch (arr[0]) {
        case "ipad.txt":
          that.form.ipAdderss = arr[1].replace(/\"/g, "");
          break;
        case "ipmk.txt":
          that.form.mask = arr[1].replace(/\"/g, "");
          break;
        case "ipgt.txt":
          that.form.gateway = arr[1].replace(/\"/g, "");
          break;
        case "ipds.txt":
          that.form.ipv4 = arr[1].replace(/\"/g, "");
          break;
        case "mqip.txt":
          that.form.mqttIp = arr[1]
            .replace(/\"/g, "")
            .replace(/\"/g, "")
            .replace(/\"/g, "")
            .replace(/\"/g, "")
            .replace(/\"/g, "");
          break;
        case "mqpt.txt":
          that.form.mqttPort = arr[1]
            .replace(/\"/g, "")
            .replace(/\"/g, "")
            .replace(/\"/g, "")
            .replace(/\"/g, "");
          break;
        case "ptip.txt":
          that.form.serviceIp = arr[1]
            .replace(/\"/g, "")
            .replace(/\"/g, "")
            .replace(/\"/g, "");
          break;
        case "ptpt.txt":
          that.form.servicePort = arr[1].replace(/\"/g, "").replace(/\"/g, "");
          break;
        case "tbox.txt":
          that.form.equipmentName = arr[1].replace(/\"/g, "");
          break;
        case "Version.txt":
          that.form.version = arr[1].replace(/\"/g, "");
          break;
        case "user.txt":
          that.form.mqttuser = arr[1].replace(/\"/g, "");
          break;
        case "pwd.txt":
          that.form.mqttpassword = arr[1].replace(/\"/g, "");
          break;
        case "connect.txt":
          let a = arr[1].replace(/\"/g, "");
          if (a == "0") {
            that.ipSelectTit = "连接指定IP";
          }
          if (a == "1") {
            that.ipSelectTit = "等待广播IP";
          }
          if (a == "2") {
            that.ipSelectTit = "广播互切";
          }
          if (a == "3") {
            that.ipSelectTit = "关闭连接";
          }
          break;
      }
    },
    // 修改设备名称
    deviceNameUp(cb) {
      let that = this;
      let out = "";
      let strings = that.form.equipmentName.replace(/\s*/g, "");
      let arr = strings.split("");
      console.log(arr);
      if (arr.length == 0) {
        uni.$u.toast("您输入的内容有误！");
      } else {
        for (let i = 0; i < arr.length; i++) {
          let num = arr[i].charCodeAt().toString(16);
          out += num;
        }
        if (this.linkStatus) {
          this.sendMy(`1020${out}00ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 修改mqtt账号
    mqttuserClick(cb) {
      let that = this;
      let out = "";
      let strings = that.form.mqttuser.replace(/\s*/g, "");
      let arr = strings.split("");
      if (arr.length == 0) {
        uni.$u.toast("您输入的内容有误！");
      } else {
        for (let i = 0; i < arr.length; i++) {
          let num = arr[i].charCodeAt().toString(16);
          out += num;
        }
        if (this.linkStatus) {
          this.sendMy(`1024${out}00ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 修改mqtt密码
    mqttpasswordClick(cb) {
      let that = this;
      let out = "";
      let strings = that.form.mqttpassword.replace(/\s*/g, "");
      let arr = strings.split("");
      if (arr.length == 0) {
        uni.$u.toast("您输入的内容有误！");
      } else {
        for (let i = 0; i < arr.length; i++) {
          let num = arr[i].charCodeAt().toString(16);
          out += num;
        }
        if (this.linkStatus) {
          this.sendMy(`1025${out}00ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 修改设备IP
    deviceIpUp(cb) {
      let that = this;
      let out = "";
      let strings = that.form.ipAdderss.replace(/\s*/g, "");
      let pd = that.isIP(strings);

      let arr = strings.split(".");
      if (!pd) {
        uni.$u.toast("您输入的内容有误！");
      } else {
        for (let i = 0; i < arr.length; i++) {
          let num = parseInt(arr[i]).toString(16);
          num.length < 2 ? (num = "0" + num) : (num = num);
          console.log(num);
          out += num;
        }
        if (this.linkStatus) {
          this.sendMy(`1011${out}00ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 修改子网掩码
    subnetMaskUpA(cb) {
      let that = this;
      let strings = that.form.mask.replace(/\s*/g, "");
      let pd = that.isIP(strings);
      let arr = strings.split(".");
      if (!pd) {
        uni.$u.toast("您输入的内容有误！");
      } else {
        let a = parseInt(arr[0]).toString(16);
        a.length < 2 ? (a = "0" + a) : (a = a);
        let b = parseInt(arr[1]).toString(16);
        b.length < 2 ? (b = "0" + b) : (b = b);
        let c = parseInt(arr[2]).toString(16);
        c.length < 2 ? (c = "0" + c) : (c = c);
        let d = parseInt(arr[3]).toString(16);
        d.length < 2 ? (d = "0" + d) : (d = d);
        if (this.linkStatus) {
          this.sendMy(`1012${a}${b}01ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    subnetMaskUpB(cb) {
      let that = this;
      let strings = that.form.mask.replace(/\s*/g, "");
      let pd = that.isIP(strings);
      let arr = strings.split(".");
      if (!pd) {
        uni.$u.toast("您输入的内容有误！");
      } else {
        let a = parseInt(arr[0]).toString(16);
        a.length < 2 ? (a = "0" + a) : (a = a);
        let b = parseInt(arr[1]).toString(16);
        b.length < 2 ? (b = "0" + b) : (b = b);
        let c = parseInt(arr[2]).toString(16);
        c.length < 2 ? (c = "0" + c) : (c = c);
        let d = parseInt(arr[3]).toString(16);
        d.length < 2 ? (d = "0" + d) : (d = d);
        if (this.linkStatus) {
          this.sendMy(`1012${c}${d}02ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 修改网关
    gatewayUp(cb) {
      let that = this;
      let out = "";
      let strings = that.form.gateway.replace(/\s*/g, "");
      let pd = that.isIP(strings);
      let arr = strings.split(".");
      if (!pd) {
        uni.$u.toast("您输入的内容有误！");
      } else {
        for (let i = 0; i < arr.length; i++) {
          let num = parseInt(arr[i]).toString(16);
          num.length < 2 ? (num = "0" + num) : (num = num);
          console.log(num);
          out += num;
        }
        if (this.linkStatus) {
          this.sendMy(`1013${out}00ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 修改IPV4
    ipv4Up(cb) {
      let that = this;
      let out = "";
      let strings = that.form.ipv4.replace(/\s*/g, "");
      let pd = that.isIP(strings);
      let arr = strings.split(".");
      if (!pd) {
        uni.$u.toast("您输入的内容有误！");
      } else {
        for (let i = 0; i < arr.length; i++) {
          let num = parseInt(arr[i]).toString(16);
          num.length < 2 ? (num = "0" + num) : (num = num);
          console.log(num);
          out += num;
        }
        if (this.linkStatus) {
          this.sendMy(`1014${out}00ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 修改mqttIp
    mqttIpUp(cb) {
      let that = this;
      let out = "";
      let strings = that.form.mqttIp.replace(/\s*/g, "");
      let pd = that.isIP(strings);
      let arr = strings.split(".");
      if (!pd) {
        uni.$u.toast("您输入的内容有误！");
      } else {
        for (let i = 0; i < arr.length; i++) {
          let num = parseInt(arr[i]).toString(16);
          num.length < 2 ? (num = "0" + num) : (num = num);
          console.log(num);
          out += num;
        }
        if (this.linkStatus) {
          this.sendMy(`1015${out}00ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 修改matt端口
    mqttPortUp(cb) {
      // 修改后的操作
      let strings = this.form.mqttPort.replace(/\s*/g, "");
      let a = parseInt(strings).toString(16).split("");
      let out = "";
      if (this.form.mqttPort == "") {
        uni.$u.toast("您输入的内容有误！");
      } else {
        if (a.length == 4) {
          console.log(`${a[2]}${a[3]}${a[0]}${a[1]}`);
          out = `${a[2]}${a[3]}${a[0]}${a[1]}`;
        }
        if (a.length == 3) {
          console.log(`${a[1]}${a[2]}0${a[0]}`);
          out = `${a[1]}${a[2]}0${a[0]}`;
        }
        if (this.linkStatus) {
          this.sendMy(`1016${out}00ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 修改服务IP
    serviceUpIp(cb) {
      let that = this;
      let out = "";
      let strings = that.form.serviceIp.replace(/\s*/g, "");
      let pd = that.isIP(strings);
      let arr = strings.split(".");
      if (!pd) {
        uni.$u.toast("您输入的内容有误！");
      } else {
        for (let i = 0; i < arr.length; i++) {
          let num = parseInt(arr[i]).toString(16);
          num.length < 2 ? (num = "0" + num) : (num = num);
          console.log(num);
          out += num;
        }
        if (this.linkStatus) {
          this.sendMy(`1021${out}00ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 修改配置端口
    servicePortUp(cb) {
      let that = this;
      let strings = that.form.servicePort.replace(/\s*/g, "");
      let a = parseInt(strings).toString(16).split("");
      let out = "";
      if (that.form.servicePort == "") {
        uni.$u.toast("您输入的内容有误！");
      } else {
        if (a.length == 4) {
          console.log(`${a[2]}${a[3]}${a[0]}${a[1]}`);
          out = `${a[2]}${a[3]}${a[0]}${a[1]}`;
        }
        if (a.length == 3) {
          console.log(`${a[1]}${a[2]}0${a[0]}`);
          out = `${a[1]}${a[2]}0${a[0]}`;
        }
        if (this.linkStatus) {
          this.sendMy(`1022${out}00ffffff`, () => {
            if (cb) {
              cb();
            }
          });
        } else {
          uni.$u.toast("请先连接蓝牙！");
        }
      }
    },
    // 打开蓝牙设备选择窗口
    openShow() {
      this.show = true;
      this.connectDeviceList = []; // 清空设备列表
      this.searchBluetoothDevicesForConnect(); // 开始搜索设备
    },
    // 关闭蓝牙设备选择窗口
    closeShow() {
      this.show = false;
      this.connectDeviceList = [];
      // 停止蓝牙搜索
      uni.stopBluetoothDevicesDiscovery({
        complete() {
          console.log("停止蓝牙搜索");
        },
      });
    },
    // 搜索蓝牙设备用于连接
    searchBluetoothDevicesForConnect() {
      let that = this;

      // 先检查定位权限
      uni.getSetting({
        success(res) {
          const locationAuth = res.authSetting["scope.userLocation"];
          console.log("定位权限状态:", locationAuth);

          if (locationAuth === false) {
            // 用户明确拒绝了权限，需要去设置页面
            uni.showModal({
              title: "需要定位权限",
              content: "蓝牙搜索需要定位权限，请到设置页面开启定位权限",
              confirmText: "去设置",
              cancelText: "取消",
              success(modalRes) {
                if (modalRes.confirm) {
                  uni.openSetting();
                }
              },
            });
            return;
          } else if (locationAuth === undefined) {
            // 用户从未被询问过权限，尝试请求权限
            console.log("首次请求定位权限");
            uni.getLocation({
              type: "wgs84",
              success() {
                console.log("定位权限授权成功");
                that.startBluetoothSearchForConnect();
              },
              fail(err) {
                console.log("定位权限授权失败:", err);
                if (err.errMsg && err.errMsg.includes("auth deny")) {
                  uni.showModal({
                    title: "权限被拒绝",
                    content: "蓝牙搜索需要定位权限，请到设置页面开启定位权限",
                    confirmText: "去设置",
                    cancelText: "取消",
                    success(modalRes) {
                      if (modalRes.confirm) {
                        uni.openSetting();
                      }
                    },
                  });
                } else {
                  // 即使定位失败，也尝试蓝牙搜索
                  uni.showToast({
                    title: "建议开启定位权限以提高蓝牙搜索成功率",
                    icon: "none",
                    duration: 3000,
                  });
                  that.startBluetoothSearchForConnect();
                }
              },
            });
            return;
          }

          // 权限已授权 (locationAuth === true)
          console.log("定位权限已授权，开始蓝牙搜索");
          that.startBluetoothSearchForConnect();
        },
        fail(err) {
          console.error("获取权限设置失败:", err);
          // 获取设置失败，仍然尝试蓝牙搜索
          that.startBluetoothSearchForConnect();
        },
      });
    },

    // 开始蓝牙搜索用于连接
    startBluetoothSearchForConnect() {
      let that = this;

      // 先检查蓝牙适配器状态
      uni.getBluetoothAdapterState({
        success(res) {
          console.log("蓝牙适配器状态:", res);
          if (res.available) {
            // 蓝牙适配器已经可用，直接开始搜索
            that.startDeviceDiscovery();
          } else {
            // 蓝牙适配器不可用，尝试初始化
            that.initBluetoothAdapter();
          }
        },
        fail() {
          // 获取状态失败，可能是适配器未初始化，尝试初始化
          console.log("获取蓝牙适配器状态失败，尝试初始化");
          that.initBluetoothAdapter();
        },
      });
    },

    // 初始化蓝牙适配器
    initBluetoothAdapter() {
      let that = this;
      uni.openBluetoothAdapter({
        success: function (res) {
          console.log("蓝牙适配器初始化成功");
          that.startDeviceDiscovery();
        },
        fail: function (msg) {
          console.log("蓝牙初始化失败:", msg);
          if (msg.errMsg && msg.errMsg.includes("already opened")) {
            // 如果是已经打开的错误，直接开始搜索
            console.log("蓝牙适配器已经打开，直接开始搜索");
            that.startDeviceDiscovery();
          } else {
            uni.showToast({
              title: "蓝牙初始化失败",
              icon: "none",
            });
          }
        },
      });
    },

    // 开始设备搜索
    startDeviceDiscovery() {
      let that = this;

      // 设置设备发现监听
      uni.onBluetoothDeviceFound(function (deviceRes) {
        deviceRes.devices.forEach((device) => {
          // 避免重复添加设备
          const existingDevice = that.connectDeviceList.find(
            (d) => d.deviceId === device.deviceId
          );
          if (!existingDevice) {
            // 计算信号距离
            device.RSSI = Math.pow(10, (-70 - (device.RSSI || 0)) / 20).toFixed(
              0
            );
            that.connectDeviceList.push(device);
          }
        });
      });

      // 先停止之前的搜索，然后开始新搜索
      uni.stopBluetoothDevicesDiscovery({
        complete() {
          // 开始搜索设备
          uni.startBluetoothDevicesDiscovery({
            services: ["FFE9", "FFE4"],
            allowDuplicatesKey: false,
            interval: 0,
            success(resd) {
              console.log("开始搜索蓝牙设备用于连接");

              // 获取已发现的设备
              uni.getBluetoothDevices({
                success: function (res) {
                  console.log("搜索到设备:", res.devices);
                  res.devices.forEach((device) => {
                    const existingDevice = that.connectDeviceList.find(
                      (d) => d.deviceId === device.deviceId
                    );
                    if (!existingDevice) {
                      device.RSSI = Math.pow(
                        10,
                        (-70 - (device.RSSI || 0)) / 20
                      ).toFixed(0);
                      that.connectDeviceList.push(device);
                    }
                  });
                },
              });
            },
            fail(err) {
              console.log("搜索失败:", err);
              uni.showToast({
                title: "蓝牙搜索失败",
                icon: "none",
              });
            },
          });
        },
      });
    },

    // 刷新设备列表
    refreshDeviceList() {
      this.connectDeviceList = [];
      this.startDeviceDiscovery();
    },

    // 判断输入的IP地址是否有误
    isIP(input) {
      const ipRegex =
        /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
      return ipRegex.test(input);
    },

    okPreserveData() {
      let that = this;

      that.$refs.uForm.validate().then((valid) => {
        if (valid) {
          if (that.linkStatus) {
            that.showSend = true;
            // 定义参数写入任务队列
            that.deviceNameUp(() => {
              that.deviceIpUp(() => {
                that.subnetMaskUpA(() => {
                  that.subnetMaskUpB(() => {
                    that.gatewayUp(() => {
                      that.ipv4Up(() => {
                        that.mqttIpUp(() => {
                          that.mqttPortUp(() => {
                            that.serviceUpIp(() => {
                              that.servicePortUp(() => {
                                that.mqttuserClick(() => {
                                  that.mqttpasswordClick(() => {
                                    setTimeout(() => {
                                      that.sendMy("100201ffffff", () => {
                                        setTimeout(() => {
                                          that.showSend = false;
                                          uni.$u.toast("参数写入完成！");
                                        }, 1000);
                                      });
                                    }, 1000);
                                  });
                                });
                              });
                            });
                          });
                        });
                      });
                    });
                  });
                });
              });
            });
            // const writeParams = [
            //   { name: "设备名称", method: that.deviceNameUp },
            //   { name: "IP地址", method: that.deviceIpUp },
            //   { name: "子网掩码A", method: that.subnetMaskUpA },
            //   { name: "子网掩码B", method: that.subnetMaskUpB },
            //   { name: "默认网关", method: that.gatewayUp },
            //   { name: "IPV4", method: that.ipv4Up },
            //   { name: "MQTT IP", method: that.mqttIpUp },
            //   { name: "MQTT端口", method: that.mqttPortUp },
            //   { name: "服务IP", method: that.serviceUpIp },
            //   { name: "配置端口", method: that.servicePortUp },
            //   { name: "MQTT用户名", method: that.mqttuserClick },
            //   { name: "MQTT密码", method: that.mqttpasswordClick },
            // ];

            // // 顺序执行参数写入
            // that.executeWriteParams(writeParams, 0);
          } else {
            uni.$u.toast("请先连接蓝牙！");
          }
        } else {
          uni.$u.toast("写入的参数有误！");
        }
      });
    },

    // 顺序执行参数写入
    executeWriteParams(writeParams, index) {
      let that = this;

      if (index >= writeParams.length) {
        // 关闭遮罩层并重置状态

        setTimeout(() => {
          setTimeout(() => {
            that.sendMy("100201ffffff");
          }, 1000);
          that.showSend = false;
          uni.$u.toast("参数写入完成！");
        }, 1000);
        return;
      }

      const currentParam = writeParams[index];
      console.log(`正在写入: ${currentParam.name}`);

      try {
        currentParam.method();

        // 间隔1000ms执行下一个参数
        setTimeout(() => {
          that.executeWriteParams(writeParams, index + 1);
        }, 1000);
      } catch (error) {
        console.error(`写入${currentParam.name}失败:`, error);
        // 即使某个参数失败，也继续执行下一个
        setTimeout(() => {
          that.executeWriteParams(writeParams, index + 1);
        }, 1000);
      }
    },
  },
};
</script>
  
  <style lang="scss">
.warp {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #fff;
  font-size: 2vh;
}

.icu-content {
  width: 750rpx;
  padding: 15rpx 15rpx 15rpx 15rpx;
  box-sizing: border-box;
  position: relative;
  z-index: 1;

  .icu-btn-box {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;

    .btn {
      width: 320rpx;
      height: 120rpx;
      margin-right: 15rpx;
      margin-bottom: 25rpx;
    }

    .btn1 {
      width: 91%;
      height: 120rpx;
      margin-right: 15rpx;
      margin-bottom: 25rpx;
    }
  }

  .icu-inp-box {
    width: 100%;
    margin-top: 25rpx;
    box-sizing: border-box;
    padding: 0 40rpx 0 40rpx;
  }
}

.loading-box {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 20000;
  pointer-events: none;
}

/* 蓝牙设备选择弹窗样式 */
.bluetooth-device-list {
  max-height: 600rpx;
  overflow-y: auto;
}

.no-device {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 60rpx 20rpx;
  color: #999;
}

.device-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #fff;
  transition: background-color 0.2s;
}

.device-item:hover {
  background-color: #f8f9fa;
}

.device-item:active {
  background-color: #e9ecef;
}

.device-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.device-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
}

.device-id {
  font-size: 24rpx;
  color: #999;
  word-break: break-all;
}

.device-signal {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.signal-strength {
  font-size: 24rpx;
  color: #666;
  background-color: #f0f0f0;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.refresh-btn {
  padding: 30rpx 20rpx;
  text-align: center;
  border-top: 1rpx solid #f0f0f0;
}
</style>
  <style scoped>
.btn >>> .u-button--large {
  height: 100% !important;
}

.btn >>> .u-button__text {
  font-size: 40rpx !important;
}

.btn >>> .u-icon__icon {
  font-size: 55rpx !important;
}

.icu-inp-box >>> .u-form-item__body {
  padding: 25rpx 0 !important;
}
</style>